<?php
$this->pageTitle=Yii::app()->name . ' - Temperature Control';
$this->breadcrumbs=array(
	'温度控制',
);
?>
<?php 
   $init_table = array();
   for($i=0;$i<=20;$i++){
      $init_table[$i] = rand(-20,50);
   }
?>
<script type="text/javascript" src="<?php echo JS_URL; ?>/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<?php echo JS_URL; ?>/highcharts.js"></script>
<script type="text/javascript" src="<?php echo JS_URL; ?>/exporting.js"></script>
<script type="text/javascript" src="<?php echo JS_URL; ?>/bplayer.js"></script>

<script  type="text/javascript" >
$(function () {                                                                     
    $(document).ready(function() {                                                  
        Highcharts.setOptions({                                                     
            global: {                                                               
                useUTC: false                                                       
            }                                                                       
        });                                                                          
        var chart;  
        var showPointNum = 20; 		//统计图显示节点数目
        var timeInterval = 5000;	//时间间隔（单位：ms）                                                              
        $('#container').highcharts({                                                
            chart: {                                                                
                type: 'spline',                                                     
                animation: Highcharts.svg, // don't animate in old IE               
                marginRight: 10,                                                    
                events: {                                                           
                    load: function() {                                              
                        // set up the updating of the chart each second             
                        var series = this.series[0]; 
                        setInterval(function() { 
                        	var x,y;   
                        	x = (new Date()).getTime();  
                        	$.ajax({
                        		type: "post",
                                url: "index.php?r=ajax/graph",
                                dataType: "json",
                                async:false,
                                success: function(result){
									y=result.info;
                                },
                            	error: function(){
									y=series.data[series.data.length-1].y;
                                }
                            });                     
                            /* var x = (new Date()).getTime(), // current time         
                                y = Math.random();    */
                           	var isShift =  (series.data.length>=showPointNum);
                            series.addPoint([x, y], true, isShift);                             
							/* if(parseInt(x/1000%5)>2)
							{
                            	series.addPoint([x, y], true, true);
							} */                    
                        }, timeInterval);                                                   
                    }                                                               
                }                                                                   
            },                                                                      
            title: {                                                                
                text: '实时监控'                                            
            },                                                                      
            xAxis: {                                                                
                type: 'datetime',                                                   
                tickPixelInterval: 100                                              
            },                                                                      
            yAxis: {                                                                
                title: {                                                            
                    text: '温度（℃）'                                                   
                },                                                                  
                plotLines: [{                                                       
                    value: 0,                                                       
                    width: 1,                                                       
                    color: '#808080'                                                
                }]                                                                  
            },                                                                      
            tooltip: {                                                              
                formatter: function() {                                             
                        return '<b>'+ this.series.name +'</b><br/>'+                
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                        Highcharts.numberFormat(this.y, 1)+"℃";                         
                }                                                                   
            },                                                                      
            legend: {                                                               
                enabled: false                                                      
            },                                                                      
            exporting: {                                                            
                enabled: false                                                      
            },                                                                      
            series: [{                                                              
                name: '温度监控',                                                
                data: (function() {                                                 
                    // generate an array of random data                             
                    var data = [],                                                  
                        time = (new Date()).getTime(),                              
                        i;                                                          
                                                                                    
                    for (i = -(showPointNum-1); i <= 0; i++) {                                    
                        data.push({                                                 
                            x: time + i * timeInterval,                                     
                            y: Math.random()*(50+20)-20                                       
                        });                                                         
                    }                                                             
                    return data;                                                    
                })()                                                                
            }]                                                                      
        });                                                                         
    });                                                                             
                                                                                    
});            
</script>

<script type="text/javascript">
<!--
$(function () {
    $('#container2').highcharts({
        chart: {
            type: 'spline'
        },
        title: {
            text: '温度控制图'
        },
        /* subtitle: {
            text: 'Irregular time data in Highcharts JS'
        }, */
        xAxis: {
        	text: '时间（min）',
        	tickInterval: 10
        },
        yAxis: {
            title: {
                text: '温度（℃）'
            }
        },
        tooltip: {
            formatter: function() {
                    return '<b>时间：</b>'+this.x+'min<br/><b>温度：</b>'+ this.y +'℃';
            }
        },
        
        series: [{
            name: '阶段温度变化',
            data: [
                <?php 
                for($i=0;$i<=20;$i++){
                    if($i!=20){
						if($i==0){
                        	echo "[".($i*5).",".$init_table[$i]."],";
						}else{
							echo "[".($i*5).",".$init_table[$i-1]."],";
							echo "[".($i*5).",".$init_table[$i]."],";
						}
                    }else{
						echo "[".($i*5).",".$init_table[$i-1]."],";
                    	echo "[".($i*5).",".$init_table[$i]."]";
                    }
                }
                ?>
            ]
        },{
            name: '走势温度变化',
            data: [
                <?php 
                for($i=0;$i<=20;$i++){
                    if($i!=20){
                        echo "[".($i*5).",".$init_table[$i]."],";
                    }else{
                    	echo "[".($i*5).",".$init_table[$i]."]";
                    }
                }
                ?>
            ]
        }]
    });
});	
//-->
</script>


<script type="text/javascript">
<!--
var p_timer;
var table_count = 0;
var time_count = 0;
var time_arr = [];
var value_arr = [];
<?php 
	for($i=0;$i<=20;$i++){
?>
		time_arr[<?php echo $i?>] = <?php echo $i*5;?>;
		value_arr[<?php echo $i?>] =  <?php echo $init_table[$i];?>;
<?php
	}
?>
function send_data(type){
	var time_interval = parseInt($('#send_rate').val());
	if(typeof p_timer !="undefined"){
		window.clearInterval(p_timer);
	}
	p_timer=window.setInterval(function(){	send_data_common(type);	},time_interval*1000);
}

function stop_send_data(){
	window.clearInterval(p_timer);
}

function send_data_common(type){
	
	var time_interval = parseInt($('#send_rate').val());
	time_count += time_interval;
	var min_count = Math.floor(time_count/60);
	var all_time = parseInt($("#all_time").val());
	if(min_count>all_time){
		alert("已完成发送数据！");
		if(typeof p_timer !="undefined"){
			window.clearInterval(p_timer);
		}
	}
	var temp_time = time_arr[1];
	var index = 1;
	while(min_count>=temp_time){
		index++;
		temp_time = time_arr[index];
	}
	var temp_value;
	if(type=="trend"){
		var k =  (value_arr[index]-value_arr[index-1])/(time_arr[index]-time_arr[index-1]);
		temp_value =k*(time_count/60-time_arr[index-1])+value_arr[index-1];
		temp_value = Math.round(temp_value*10)/10;
	}else{
		temp_value = value_arr[index-1];
	}
	
	$('#time_text').html("已发送时间："+time_count+"s");
	$('#value_text').html("当前发送数据："+temp_value+"℃");
	
	var select_port = $('#select_port').val();
	var port_rate = $('#port_rate').val();
	var data_bit = $('#data_bit').val();
	var stop_bit = $('#stop_bit').val();
	var parity = $('#parity').val();	
	
	$.ajax({
		type: "post",
        url: "index.php?r=temperature/Senddata",
        dataType: "json",
		data: "comport="+select_port+"&port_rate="+port_rate+"&data_bit="+data_bit+"&stop_bit="+stop_bit+"&parity="+parity+"&value="+temp_value,
        //async:false,
        success: function(result){
			//alert("success");
        },
    	error: function(){
			//alert("error");
        }
    });  
}

function check_input_time(){
    var all_time = $("#all_time").val();
    var re = /^[1-9]+[0-9]*]*$/;
    if (!re.test(all_time)){  
       alert("请输入正确的控温时间！");  
       $("#all_time").val("100");  
       $("#all_time")[0].focus();  
       return false;  
    }  
}

function check_input(id){
	//alert(id);
	var value = $("#"+id).val();
	if(isNaN(value)){
		alert("请输入数字!");
		$("#"+id).val("0");
		return false;
	}
}

function create_table(){
	var all_time = $("#all_time").val();
	var rate  =  $("#control_rate").val();

	var max = parseInt($('#max_temp').val());
	var min = parseInt($('#min_temp').val());
    table_count = Math.floor(all_time/rate);
    var range = max - min;
    var time_rate = parseInt($("#control_rate").val());
	//console.log(time_rate);
	var html = '<div style="float: left;" ><span style="margin-left: 10px; width:50px;">时间(min)</span><span style="margin-left: 10px; width:50px;">温度(℃)</span></div>'
	for(var i=0;i<=table_count;i++){
		var temp = Math.round(Math.random()*range)+min;
		html += '<div style="float: left;width:190px;" id="table_row_'+i+'" >';
		html += '<input type="text" id="table_time_'+i+'" size="3" value="'+(i*time_rate)+'" onchange="check_input(this.id)" onblur="change_time_value('+i+')" style="margin-left: 10px;width:50px;">';
		html += '<input type="text" id="table_value_'+i+'" size="3" value="'+temp+'" onchange="check_input(this.id)" onblur="change_temp_value('+i+')" style="margin-left:10px;width:50px;">';
		html += '</div>';
	}
	$('#table_group').html(html);
	
    for(var i=0;i<=table_count;i++){
        //console.log($('#table_row_'+i).html());
    	time_arr[i]=parseInt($('#table_time_'+i).val());
    	value_arr[i]=parseFloat($('#table_value_'+i).val());
    }
    time_arr.length = table_count + 1;
    value_arr.length = table_count + 1;
}

function change_time_value(i){
	if(!isNaN($('#table_time_'+i).val())){
		time_arr[i]=parseInt($('#table_time_'+i).val());
	}
}

function change_temp_value(i){
	if(!isNaN($('#table_time_'+i).val())){
		value_arr[i]=parseFloat($('#table_value_'+i).val());
	}
}

function refresh_comport(){
	$.ajax({
		type: "post",
        url: "index.php?r=temperature/getport",
        dataType: "json",
        //async:false,
        success: function(result){
            if(result.status==1){
                $('#select_port').empty();
                for(var key in result.info){
                	 $('#select_port').append("<option value='"+key+"'>"+result.info[key]+"</option>");
                }
                alert(result.msg);    
            }else{
                alert(result.msg);  
            }
        },
    	error: function(){
			alert("error");
        }
    });  
}

function reset_table(){

	$('#all_time').val('100');
	$('#max_temp').val('50');
	$('#min_temp').val('-20');

	$("#control_rate option[value='5']").attr("selected",true);
	$("#send_rate option[value='1']").attr("selected",true);

	create_table();
}

function create_graph(){
    
    //console.log(time_arr);console.log(value_arr);
    draw_graph("container2",time_arr,value_arr);
}

function draw_graph(id,x_value,y_value){
	$('#'+id).highcharts({
        chart: {
            type: 'spline'
        },
        title: {
            text: '温度控制图'
        },
        /* subtitle: {
            text: 'Irregular time data in Highcharts JS'
        }, */
        xAxis: {
        	text: '时间（min）',
        	tickInterval: 10
        },
        yAxis: {
            title: {
                text: '温度（℃）'
            }
        },
        tooltip: {
            formatter: function() {
                    return '<b>时间：</b>'+this.x+'min<br/><b>温度：</b>'+ this.y +'℃';
            }
        },
        
        series: [{
            name: '阶段温度变化',
            data: (function() {                                                 
                // generate an array of random data                             
                var data = [];                                              
                                                                                
                for (var i=0;i<x_value.length;i++) {   
					if(i==0){                                 
						data.push({                                                 
							x: x_value[i],                                     
							y: y_value[i]                                      
						});
					}else{
						data.push({                                                 
							x: x_value[i],                                     
							y: y_value[i-1]                                      
						});
						data.push({                                                 
							x: x_value[i],                                     
							y: y_value[i]                                      
						});
					}                                                         
                }                                                             
                return data;                                                    
            })()           
        },{
            name: '走势温度变化',
            data: (function() {                                                 
                // generate an array of random data                             
                var data = [];                                              
                                                                                
                for (var i=0;i<x_value.length;i++) {                                    
                    data.push({                                                 
                        x: x_value[i],                                     
                        y: y_value[i]                                      
                    });                                                         
                }                                                             
                return data;                                                    
            })()           
        }]
    });
}
//-->
</script>




<h1>温度控制</h1>

<div style="float:left;width:150px;" class="portlet-content">
    <div class="portlet-decoration">
        <div class="portlet-title">串口选择</div>
    </div>
    <div style="margin-top: 5px;margin-left:5px;">
        <ul class="operations">
          <li>串口编号：
              <label>
              <select name="select_port" id="select_port" style="width: 72px;">
                <option value="1">COM1</option>
                <option value="2">COM2</option>
                <option value="3">COM3</option>
                <option value="4">COM4</option>
                <option value="5">COM5</option>
                <option value="6">COM6</option>
                <option value="7">COM7</option>
                <option value="8">COM8</option>
              </select>
              </label>
          </li>
           <li> 波 特 率 ：
            <label>
              <select name="port_rate" id="port_rate" style="width: 72px;">
                <option value="110">110</option>
                <option value="300">300</option>
                <option value="600">600</option>
                <option value="1200">1200</option>
                <option value="2400">2400</option>
                <option value="4800">4800</option>
                <option value="9600">9600</option>
                <option value="38400" selected="selected">38400</option>
                <option value="56000">56000</option>
                <option value="57600">57600</option>
                <option value="115200">115200</option>
                <option value="128000">128000</option>
                <option value="250000">250000</option>
                <option value="256000">256000</option>
              </select>
              </label>
           </li>
            <li> 数 据 位 ：
            <label>
              <select name="data_bit" id="data_bit" style="width: 72px;">
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8" selected="selected">8</option>
              </select>
              </label>
           </li>
            <li> 停 止 位 ：
            <label>
              <select name="stop_bit" id="stop_bit" style="width: 72px;">
                <option value="1" selected="selected">1</option>
                <option value="1.5">1.5</option>
                <option value="2">2</option>
              </select>
              </label>
           </li>
            <li> 校 验 位 ：
            <label>
              <select name="parity" id="parity" style="width: 72px;">
                <option value="Even">Even</option>
                <option value="Mark">Mark</option>
                <option value="Odd">Odd</option>
                <option value="Space">Space</option>
                <option value="None" selected="selected">None</option>
              </select>
              </label>
           </li>
           <li>
               <input type="button" onclick="refresh_comport()" value="&nbsp;查找服务器串口&nbsp;">
           </li>
           <li>
               <input type="button" onclick="send_data('trend')" value="发送走势控温数据">
           </li>
		    <li>
               <input type="button" onclick="send_data('period')" value="发送阶段控温数据">
           </li>
		    <li>
               <input type="button" onclick="stop_send_data()" value="暂时发送控温数据">
           </li>
		    <li id="time_text">
               已发送时间：0s 
           </li>
		   <li id="value_text">
               当前发送数据：空
           </li>
       </ul>
    </div>

    <br clear="all">
    <div class="portlet-decoration">
        <div class="portlet-title">参数控制</div>
    </div>
    <div style="margin-top: 5px;margin-left:5px;">
        <ul class="operations">
          <li> 控温时间：<input type="text" size="5" name="all_time" id="all_time" onchange="check_input_time()" value="100" style="width:32px;"> (分钟)
          <li>控温频率：
            <label>
              <select name="control_rate" id="control_rate" >
                <option value="1">1分钟</option>
                <option value="2">2分钟</option>
                <option value="3">3分钟</option>
                <option value="4">4分钟</option>
                <option value="5" selected="selected">5分钟</option>
                <option value="6">6分钟</option>
                <option value="10">10分钟</option>
                <option value="12">12分钟</option>
                <option value="15">15分钟</option>
                <option value="20">20分钟</option>
                <option value="30">30分钟</option>
                <option value="60">60分钟</option>
              </select>
            </label> 
          </li>
          <li>最高温度：
                <input type="text" size="5" name="max_temp" id="max_temp" onchange="check_input(this.id)" value="50"  style="width:32px;">℃ 
          </li>
          <li>最低温度：
                <input type="text" size="5" name="min_temp" id="min_temp" onchange="check_input(this.id)" value="-20"  style="width:32px;">℃ 
          </li>
           <li>发送间隔：
            <label>
              <select name="send_rate" id="send_rate" onchange="send_data()">
                <option value="1">1s</option>
                <option value="2">2s</option>
                <option value="3">3s</option>
                <option value="4">4s</option>
                <option value="5" selected="selected">5s</option>
                <option value="6">6s</option>
                <option value="10">10s</option>
                <option value="12">12s</option>
                <option value="15">15s</option>
                <option value="20">20s</option>
                <option value="30">30s</option>
                <option value="60">60s</option>
              </select>
            </label> 
           </li>
           <li>
                <input type="button" onclick="create_table()" value="确定生成数据表格">
            </li>
            <li>
                <input type="button" onclick="reset_table()" value="恢复默认数据表格">
            </li>
			
          
       </ul>
    
   
   
    </div>
    
</div>	

<div style="float:left;width:150px;margin-left:10px;" class="portlet-content">
    <div class="portlet-decoration">
        <div class="portlet-title"> 
           <span >                
                           温度控制
           </span>               
        </div>
    </div>
    <br clear="all">
    <label>
    <input type="button" onclick="create_graph()" value="生成控温曲线图" style="margin-left: 10px;">
    </label>
    <br clear="all">
    <div id="table_group" style="margin-top:5px;">
        <div style="float: left;" >
            <span style="margin-left: 10px; width:50px;">时间(min)</span>
            <span style="margin-left: 10px; width:50px;">温度(℃)</span>  
        </div>
    <?php 
    for($i=0;$i<=20;$i++){
    ?>
        <div style="float: left;width:190px;"  id="table_row_<?php echo $i;?>" >
           <input type="text" id="table_time_<?php echo $i;?>" size="3" value="<?php echo $i*5?>" onchange="check_input(this.id)" onblur="change_time_value(<?php echo $i;?>)" style="margin-left: 10px;width:50px;">
           <input type="text" id="table_value_<?php echo $i;?>" size="3" value="<?php echo $init_table[$i]?>" onchange="check_input(this.id)" onblur="change_temp_value(<?php echo $i;?>)" style="margin-left:10px;width:50px;">
        </div>
    <?php 
    }
    ?>
    
    </div>
</div>

<div style="float:left;margin-left:10px;min-height:485px;width:540px;" class="portlet-content">
    
    <div class="portlet-decoration" style="margin-top:10px;">
        <div class="portlet-title">温度控制</div>
    </div>
    <div class="portlet-content">
        <div id="container2" style="width:520px;height:225px;float:left"></div>
    </div>
    
    <br clear="all">
    <br />
    
    <div class="portlet-decoration">
        <div class="portlet-title">温度监控</div>
    </div>
    <div class="portlet-content">
        <div id="container" style="width:520px;height:225px;float:left"></div>
    </div>
    
    
</div>